#pragma once

#include <Windows.h>
#include <wrl.h>
#include <wrl/client.h>
#include <robuffer.h>
#include <Stringapiset.h>
#include <vector>

namespace DXBase
{
	namespace Loader
	{

		inline HRESULT HR2Ex(HRESULT hr)
		{
			if (FAILED(hr))
			{
				// Set a breakpoint on this line to catch Win32 API errors.
				throw Platform::Exception::CreateException(hr);
			}
			return hr;
		}

		inline byte* GetData(Windows::Storage::Streams::IBuffer^ buffer)
		{
			// Cast to Object^, then to its underlying IInspectable interface.
			Platform::Object^ obj = buffer;
			Microsoft::WRL::ComPtr<IInspectable> insp(reinterpret_cast<IInspectable*>(obj));
 
			// Query the IBufferByteAccess interface.
			Microsoft::WRL::ComPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
			HR2Ex(insp.As(&bufferByteAccess));
 
			// Retrieve the buffer data.
			byte* pixels = nullptr;
			HR2Ex(bufferByteAccess->Buffer(&pixels));
			return pixels;
		}

		std::vector<char> ToCString(Platform::String^ file)
		{
			// turn it into a char*
			int nc = ::WideCharToMultiByte(CP_UTF8, 0, file->Data(), file->Length(), NULL, 0, 0, 0);
			std::vector<char> cpath;
			cpath.resize(nc + 1);
			::WideCharToMultiByte(CP_UTF8, 0, file->Data(), file->Length(), &cpath[0], nc, 0, 0);
			return cpath;
		}
		Platform::String^ ToWString(std::vector<char> str)
		{
			// turn it into a char*
			int nc = ::MultiByteToWideChar(CP_UTF8, 0, &str[0], str.size(), NULL, 0);
			std::vector<wchar_t> res;
			res.resize(nc + 1);
			::MultiByteToWideChar(CP_UTF8, 0, &str[0], str.size(), &res[0], nc);
			return ref new Platform::String(&res[0]);
		}
		Platform::String^ ToWString(std::string str)
		{
			// turn it into a char*
			int nc = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), NULL, 0);
			std::vector<wchar_t> res;
			res.resize(nc + 1);
			::MultiByteToWideChar(CP_UTF8, 0, &str[0], str.length(), &res[0], nc);
			return ref new Platform::String(&res[0]);
		}
	}
}